package com.zmx.mq.task.messaging.receiver;

import com.zmx.mq.task.business.dto.RequestLogDto;
import com.zmx.mq.task.business.service.RequestLogService;
import com.zmx.common.common.contents.MqQueueContents;
import com.zmx.mq.task.common.receiver.ReceiverListener;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Map;

/**
 * @Description: 监听所有请求微服务接口消息队列
 * @ClassName: ReceiverRequestLogListener
 * @Author zhaomxr
 * @Date 2021-11-12 16:17
 */
@Slf4j
@Component
@RabbitListener(queues = MqQueueContents.SAVE_REQUEST_LOG_QUEUE)
public class ReceiverRequestLogListener implements ReceiverListener {

    @Autowired
    private RequestLogService requestLogService;

    @RabbitHandler
    @Override
    public void onMessage(@Payload Map<String, String> data) {
        log.info("onMessage {} -> data: {}", MqQueueContents.SAVE_REQUEST_LOG_QUEUE, data);
        if (data != null) {
            try {
                RequestLogDto requestLogDto = new RequestLogDto();
                requestLogDto.setUserId(Long.valueOf(data.get("userId")));
                requestLogDto.setUserName(data.get("userName"));
                requestLogDto.setToken(data.get("token"));
                requestLogDto.setCreator(data.get("userName"));
                long createTimeL = data.get("createTime") == null ? System.currentTimeMillis() : Long.parseLong(data.get("createTime"));
                Date date = new Date(createTimeL);
                requestLogDto.setCreateTime(date);
                requestLogDto.setModifyTime(date);
                requestLogDto.setDr(0);
                requestLogService.create(requestLogDto);
            } catch (Exception e) {
                log.error("{}", e);
                log.error("保存失败！", e.getMessage());
            }
        }
    }

}
